<?php
/**
 * @file
 */
/**
 * Menu callback
 */
function cjcoupon_extend_settings($form, &$form_state) {
  $form['cjcoupon_extend_enable_generate'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable generate'),
    '#default_value' => variable_get('cjcoupon_extend_enable_generate', FALSE)
  );
  $form['cjcoupon_extend_content_type'] = array(
    '#type' => 'textfield',
    '#title' => t('Content type'),
    '#default_value' => variable_get('cjcoupon_extend_content_type', '')
  );
  $form['cjcoupon_extend_num_nodes'] = array(
    '#type' => 'textfield',
    '#title' => t('How many nodes would you like to generate? '),
    '#default_value' => variable_get('cjcoupon_extend_num_nodes', 10)
  );
  $form['cjcoupon_extend_title_length'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum number of words in titles'),
    '#default_value' => variable_get('cjcoupon_extend_title_length', 4)
  );
  $form['cjcoupon_extend_field_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Field name'),
    '#default_value' => variable_get('cjcoupon_extend_field_name', ''),
    '#description' => t('The name of field image in content type')
  );
  $form['cjcoupon_extend_default_image'] = array(
    '#type' => 'textfield',
    '#title' => t('Default Image'),
    '#default_value' => variable_get('cjcoupon_extend_default_image', ''),
  );
  $form['#validate'][] = 'cjcoupon_extend_settings_validate';
  return system_settings_form($form);
}

/**
 * Validation callback for cjcoupon_extend_settings form.
 */
function cjcoupon_extend_settings_validate($form, &$form_state) {
  $values = $form_state['values'];
  $field_name = $values['cjcoupon_extend_field_name'];
  $bundle_name = $values['cjcoupon_extend_content_type'];
  $file_url = $values['cjcoupon_extend_default_image'];
  $num_nodes = $values['cjcoupon_extend_num_nodes'];
  if (empty($bundle_name) && $field_name) {
    form_set_error('cjcoupon_extend_content_type', t('<em>Content type</em> invalidate'));
  }
  if (!is_numeric($num_nodes)) {
    form_set_error('cjcoupon_extend_num_nodes', t('Num nodes must be numeric'));
  }
  if ($num_nodes < 0) {
    form_set_error('cjcoupon_extend_num_nodes', t('Num nodes invalidate (must be greater than zero)'));
  }
  if (!empty($field_name)) {
    $instance = field_info_instance('node', $field_name, $bundle_name);
    if (!$instance) {
      form_set_error('cjcoupon_extend_field_name', t('Field <em>%name</em> must be in Content types <em>%type</em>.', array('%name' => $field_name, '%type' => $bundle_name)));
    }
  }
  if (!empty($file_url)) {
    // Check if file exists.
    $request = drupal_http_request($file_url, array('method' => 'HEAD'));
    if ($request->code != 200) {
      form_set_error('cjcoupon_extend_default_image', t('<em>%file_url</em> invalidate.', array('%file_url' => $file_url)));
    }
  }
}